package com.linkage.jz.bankruptcy.fragment.Vote;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Vote.ProVoteCreateResultActivity;
import com.linkage.jz.bankruptcy.activity.Vote.ProVoteResultFileActivity;
import com.linkage.jz.bankruptcy.activity.Vote.ProVoteVotersDetailActivity_Manager;
import com.linkage.jz.bankruptcy.base.BaseActivity;
import com.linkage.jz.bankruptcy.bean.Vote.ProVote;
import com.linkage.jz.bankruptcy.bean.Vote.ProVoteDetail;
import com.linkage.jz.bankruptcy.bean.Vote.ProVoteStatistics;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.utils.LogUtil;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.utils.ScreenUtils;
import com.linkage.jz.bankruptcy.utils.Utils;
import com.linkage.jz.bankruptcy.widget.pieView.PieData;
import com.linkage.jz.bankruptcy.widget.pieView.PieView;
import com.linkage.seapeak.utils.CommonUtils;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author AFAP
 * 表决详情页Tab-表决进度
 */
public class ProVoteDetailRateFragment_Manager extends ProVoteBaseFragment {
    public static final String TAG = "ProVoteDetailRateFragment";
    public static final String ARG_PARAM_ID = "arg_param_id";

    private TextView vote_rate_state, vote_rate_state_tip;
    private Button btn_vote_send_file;


    private ProVoteDetail mProVoteDetail;
    private List<ProVoteStatistics> mProVoteStatisticsList = new ArrayList<>();
    private String mID = "";

    private LinearLayout mLinearLayout;
    //View动态数组
    private List<View> mViewList = new ArrayList<>();
    private List<ImageView> mDots;
    private MyAdapter mAdapter;

    SwipeRefreshLayout swipeRefreshLayout;

    public static ProVoteDetailRateFragment_Manager newInstance(String id) {
        ProVoteDetailRateFragment_Manager fragment = new ProVoteDetailRateFragment_Manager();
        Bundle args = new Bundle();
        args.putSerializable(ARG_PARAM_ID, id);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mID = getArguments().getString(ARG_PARAM_ID);
    }

    public SwipeRefreshLayout getSwipeRefreshLayout() {
        return swipeRefreshLayout;
    }

    public void setSwipeRefreshLayout(SwipeRefreshLayout swipeRefreshLayout) {
        this.swipeRefreshLayout = swipeRefreshLayout;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_pro_vote_detai_rate, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        vote_rate_state = getView().findViewById(R.id.vote_rate_state);
        vote_rate_state_tip = getView().findViewById(R.id.vote_rate_state_tip);

        btn_vote_send_file = getView().findViewById(R.id.btn_vote_send_file);

        ViewPager mViewPager = getView().findViewById(R.id.vote_rate_viewpager);
        mLinearLayout = getView().findViewById(R.id.vote_rate_linear);
        mAdapter = new MyAdapter();
        mViewPager.setAdapter(mAdapter);
        mViewPager.addOnPageChangeListener(new MyOnPageChangeListener());

        Timer mTimer =  new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                if(mProVoteDetail!= null){
                    LogUtil.w(TAG,"定时刷新");
                    refreshInfo(mProVoteDetail);
                }
            }
        },4000,6000);
    }

    public void refreshInfo(ProVoteDetail bean) {
        mProVoteDetail = bean;

        String str =  ProVote.STATUS.get(mProVoteDetail.getStatus());
        if("已结束".equalsIgnoreCase(str)||"已通过".equalsIgnoreCase(str)||"未通过".equalsIgnoreCase(str))
        {
            if(mProVoteDetail.getResultStatus()==0)
            {
                str = str+"(未发布)";
            }
        }


        vote_rate_state.setText(str);
        if (mProVoteDetail.getStatus() == ProVote.STATUS_WFC) {
            vote_rate_state.setTextColor(getResources().getColor(R.color.pro_vote_status_wfc));
            vote_rate_state_tip.setText("表决还未发出哦，没有进度数据~");
            vote_rate_state_tip.setVisibility(View.VISIBLE);
        } else if (mProVoteDetail.getStatus() == ProVote.STATUS_WKS) {
            vote_rate_state.setTextColor(getResources().getColor(R.color.pro_vote_status_wks));
            vote_rate_state_tip.setText("表决还未开始哦，没有进度数据~");
            vote_rate_state_tip.setVisibility(View.VISIBLE);
        } else if (mProVoteDetail.getStatus() == ProVote.STATUS_JXZ) {
            vote_rate_state.setTextColor(getResources().getColor(R.color.pro_vote_status_jxz));
            getDetail();
        } else if (mProVoteDetail.getStatus() == ProVote.STATUS_YJS) {
            btn_vote_send_file.setVisibility(View.VISIBLE);
            if (TextUtils.isEmpty(mProVoteDetail.getResultId())) {
                btn_vote_send_file.setText("发布表决结果文件");
                btn_vote_send_file.setBackgroundResource(R.drawable.bg_btn_common_orange);
                btn_vote_send_file.setOnClickListener(v -> {
                    Intent intent = new Intent(getActivity(), ProVoteCreateResultActivity.class);
                    intent.putExtra(ProVoteCreateResultActivity.KEY_VOTE, mProVoteDetail);
                    startActivity(intent);
                });
            } else {
                btn_vote_send_file.setText("查看表决结果文件");
                btn_vote_send_file.setBackgroundResource(R.drawable.bg_btn_common);
                btn_vote_send_file.setOnClickListener(v -> {
                    Intent intent = new Intent(getActivity(), ProVoteResultFileActivity.class);
                    intent.putExtra(ProVoteResultFileActivity.KEY_VOTE, mProVoteDetail);
                    intent.putExtra(BaseActivity.KEY_PROJECTID, mProVoteDetail.getBankruptcyProjectId());
                    startActivity(intent);
                });
            }

            getDetail();
        } else if (mProVoteDetail.getResultStatus() == 1) { // 已发布
            btn_vote_send_file.setVisibility(View.VISIBLE);
            btn_vote_send_file.setText("查看表决结果文件");
            btn_vote_send_file.setBackgroundResource(R.drawable.bg_btn_common);
            btn_vote_send_file.setOnClickListener(v -> {
                Intent intent = new Intent(getActivity(), ProVoteResultFileActivity.class);
                intent.putExtra(ProVoteResultFileActivity.KEY_VOTE, mProVoteDetail);
                intent.putExtra(BaseActivity.KEY_PROJECTID, mProVoteDetail.getBankruptcyProjectId());
                startActivity(intent);
            });
            getDetail();
        } else {
            getDetail();
        }
    }


    private void loadInfo() {
        mViewList.clear();
        for (int i = 0; i < mProVoteStatisticsList.size(); i++) {
            ProVoteStatistics bean = mProVoteStatisticsList.get(i);

            LayoutInflater inflater = getLayoutInflater();
            View v = inflater.inflate(R.layout.pro_vote_view_vote_rate_manager, null);
            initCircleData(v, bean, i);
            mViewList.add(v);
        }

        mAdapter.notifyDataSetChanged();
        addIndicator();
    }

    private void initCircleData(View view, ProVoteStatistics info, int index) {
        ((TextView) view.findViewById(R.id.tv_group_name)).setText(info.getGroupName() + "表决概况");
        view.findViewById(R.id.goto_detail).setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), ProVoteVotersDetailActivity_Manager.class);
            intent.putExtra(ProVoteVotersDetailActivity_Manager.KEY_VOTE, mProVoteDetail);
            startActivity(intent);
        });
        if (index > 0) {
            view.findViewById(R.id.goto_detail).setVisibility(View.GONE);
        }

        NumberFormat percentFormat = NumberFormat.getPercentInstance();
        percentFormat.setMaximumFractionDigits(2); //最大小数位数
        percentFormat.setMinimumFractionDigits(2); //最小小数位数
        //设置第一个饼状图数据
        PieView pieView1 = view.findViewById(R.id.pieView1);
        ArrayList<PieData> pieDataList1 = new ArrayList<>();
        PieData pieData11 = new PieData("同意", info.getAgreedVoterRate());
        PieData pieData12 = new PieData("不同意", info.getDisAgreedVoterRate());
        PieData pieData13 = new PieData("未参会", info.getNotAtdVoterRate());
        pieData11.setColor(getResources().getColor(R.color.pro_vote_color_agree));
        pieData12.setColor(getResources().getColor(R.color.pro_vote_color_not_agree));
        pieData13.setColor(getResources().getColor(R.color.pro_vote_color_not_join));
        pieDataList1.add(pieData11);
        pieDataList1.add(pieData12);
//        pieDataList1.add(pieData13);

        // 参会未表决默认同意
        if (info.isDefaultAgreed()) {
            view.findViewById(R.id.area_not_vote).setVisibility(View.GONE);
        } else {
            PieData pieData14 = new PieData("参会未表决", info.getNoVoteRate());
            pieData14.setColor(getResources().getColor(R.color.pro_vote_color_not_vote));
            pieDataList1.add(pieData14);
        }
        pieView1.setData(pieDataList1);


        ((TextView) view.findViewById(R.id.tv_vote_rate_totalMembers)).setText(info.getTotalMeetingMember() + "人");
        ((TextView) view.findViewById(R.id.pro_vote_agree_number)).setText(info.getAgreedNum() + "人");
        ((TextView) view.findViewById(R.id.pro_vote_agree_percent)).setText("占比" + percentFormat.format(info.getAgreedVoterRate()));
        ((TextView) view.findViewById(R.id.pro_vote_not_agree_number)).setText(info.getDisAgreedNum() + "人");
        ((TextView) view.findViewById(R.id.pro_vote_not_agree_percent)).setText("占比" + percentFormat.format(info.getDisAgreedVoterRate()));
        ((TextView) view.findViewById(R.id.pro_vote_not_vote_number)).setText(info.getNoVoteNum() + "人");
        ((TextView) view.findViewById(R.id.pro_vote_not_vote_percent)).setText("占比" + percentFormat.format(info.getNoVoteRate()));
//        ((TextView) view.findViewById(R.id.pro_vote_not_join_number)).setText(info.getNotAttendNum() + "人");
//        ((TextView) view.findViewById(R.id.pro_vote_not_join_percent)).setText("占比" + percentFormat.format(info
//        .getNotAtdVoterRate()));


        //设置第二个饼状图数据
        PieView pieView2 = view.findViewById(R.id.pieView2);
        ArrayList<PieData> pieDataList2 = new ArrayList<>();
        PieData pieData21 = new PieData("同意", info.getAgreedMoneyRate());
        PieData pieData22 = new PieData("不同意", info.getDisAgreedMoneyRate());
        PieData pieData23 = new PieData("未参会", info.getNotAtdMoneyRate());
        pieData21.setColor(getResources().getColor(R.color.pro_vote_color_agree));
        pieData22.setColor(getResources().getColor(R.color.pro_vote_color_not_agree));
        pieData23.setColor(getResources().getColor(R.color.pro_vote_color_not_join));
        pieDataList2.add(pieData21);
        pieDataList2.add(pieData22);
        pieDataList2.add(pieData23);
        // 参会未表决默认同意
        if (info.isDefaultAgreed()) {
            view.findViewById(R.id.area_money_not_vote).setVisibility(View.GONE);
        } else {
            PieData pieData24 = new PieData("参会未表决", info.getNoVoteMoneyRate());
            pieData24.setColor(getResources().getColor(R.color.pro_vote_color_not_vote));
            pieDataList2.add(pieData24);
        }
        pieView2.setData(pieDataList2);

        ((TextView) view.findViewById(R.id.tv_vote_rate_totalMoney)).setText(CommonUtils.resetMoney(info.getTotalAmount()) + "元");
        ((TextView) view.findViewById(R.id.pro_vote_money_agree_number)).setText(CommonUtils.resetMoney(info.getAgreedAmount()) + "元");
        ((TextView) view.findViewById(R.id.pro_vote_money_agree_percent)).setText("占比" + percentFormat.format(info.getAgreedMoneyRate()));
        ((TextView) view.findViewById(R.id.pro_vote_money_not_agree_number)).setText(CommonUtils.resetMoney(info.getDisAgreedAmount()) + "元");
        ((TextView) view.findViewById(R.id.pro_vote_money_not_agree_percent)).setText("占比" + percentFormat.format(info.getDisAgreedMoneyRate()));
        ((TextView) view.findViewById(R.id.pro_vote_money_not_join_number)).setText(CommonUtils.resetMoney(info.getNotAttendAmount()) + "元");
        ((TextView) view.findViewById(R.id.pro_vote_money_not_join_percent)).setText("占比" + percentFormat.format
        (info.getNotAtdMoneyRate()));
        ((TextView) view.findViewById(R.id.pro_vote_money_not_vote_number)).setText(CommonUtils.resetMoney(info.getNoVoteAmount()) + "元");
        ((TextView) view.findViewById(R.id.pro_vote_money_not_vote_percent)).setText("占比" + percentFormat.format(info.getNoVoteMoneyRate()));
    }

    private void addIndicator() {
        mDots = new ArrayList<>();
        mLinearLayout.removeAllViews();
        for (int i = 0; i < mViewList.size(); i++) {
            ImageView imageView = new ImageView(getActivity());
            int width = ScreenUtils.dip2px(getActivity(), 8);
            int height = ScreenUtils.dip2px(getActivity(), 8);
            int margin = ScreenUtils.dip2px(getActivity(), 5);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, height);
            params.setMargins(margin, margin, margin, margin);//设置margin,也就是外边距。
            imageView.setLayoutParams(params);//传入参数params设置宽和高
            imageView.setImageResource(R.drawable.pro_vote_viewpager_indicate_not_choose);//设置图片
            mLinearLayout.addView(imageView);//将图片添加到布局中
            //将dot添加到dots集合中
            mDots.add(imageView);
        }
        mDots.get(0).setImageResource(R.drawable.pro_vote_viewpager_indicate_choose);//设置启动后显示的第一个点
    }

    class MyAdapter extends PagerAdapter {
        //大小
        @Override
        public int getCount() {
            return mViewList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            //获取图片view
            View view = mViewList.get(position);
            //设置到容器,也就是ViewPager
            container.addView(view);
            //返回控件
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            //从容器中删除
            container.removeView(mViewList.get(position));
        }
    }

    class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            for (ImageView imageView : mDots) {
                imageView.setImageResource(R.drawable.pro_vote_viewpager_indicate_not_choose);
            }
            //设置当前显示的页面的dot设置为dot_focused
            mDots.get(position).setImageResource(R.drawable.pro_vote_viewpager_indicate_choose);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            if(state == 1) {
                swipeRefreshLayout.setEnabled(false);//设置不可触发
            }else if(state == 2){
                swipeRefreshLayout.setEnabled(true);//设置可触发
            }
        }
    }

    private void getDetail() {
//        showLoading();
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        Network
                .getAPIService()
                .getVoteSchedule_Manager(userToken, mID)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        hideLoading();
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        JsonObject data = json.getAsJsonObject("data");
                        boolean defaultAgreed = data.get("defaultAgreed").getAsBoolean();
                        JsonArray groupsList = data.getAsJsonArray("dataList");
                        mProVoteStatisticsList.clear();
                        if (groupsList != null) {
                            for (int i = 0; i < groupsList.size(); i++) {
                                ProVoteStatistics bean = ProVoteStatistics.parse(groupsList.get(i).getAsJsonObject());
                                bean.setDefaultAgreed(defaultAgreed);
                                mProVoteStatisticsList.add(bean);
                            }
                        } else {
                            ProVoteStatistics bean = ProVoteStatistics.parse(data);
                            bean.setGroupName("");
                            mProVoteStatisticsList.add(bean);
                        }
                        int status = data.get("status").getAsInt();
                        String str = ProVote.STATUS.get(status);

                        if("已结束".equalsIgnoreCase(str)||"已通过".equalsIgnoreCase(str)||"未通过".equalsIgnoreCase(str))
                        {
                            if(mProVoteDetail.getResultStatus()==0)
                            {
                                str = str+"(未发布)";
                            }
                        }
                        vote_rate_state.setText(str);
                        loadInfo();
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideLoading();
                        super.onError(e);
                    }
                });
    }
}
